package com.weakteam.orderonline.webclient.web;


import com.weakteam.orderonline.dataresource.domain.ClientOrder;
import com.weakteam.orderonline.dataresource.domain.ClientOrderContent;
import com.weakteam.orderonline.dataresource.domain.Place;
import com.weakteam.orderonline.dataresource.service.ClientOrderService;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * @author Nail
 */

@Controller
public class OrderNetService {
    private static final Logger log = LoggerFactory.getLogger(OrderNetService.class);

    @Autowired
    private ClientOrderService clientOrderService;

    private static void initJSONHeader(final HttpServletResponse httpResponse){
        httpResponse.setHeader("Connection", "close");
        httpResponse.setHeader("Content-Type", "application/json");
        httpResponse.setHeader("Expires", "Thu, 19 Nov 1981 08:52:00 GMT");
        httpResponse.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
        httpResponse.setHeader("Pragma", "no-cache");
        httpResponse.setCharacterEncoding("UTF-8");
    }

    @RequestMapping(value = "/addOrder")
    public void addOrder(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse) {
        try {

            String json = httpRequest.getParameter("data");

            initJSONHeader(httpResponse);
            PrintWriter out = httpResponse.getWriter();

            if (json != null && json.length() > 0){
                try {
                    JSONParser parser = new JSONParser();
                    JSONObject jObj = (JSONObject)parser.parse(json);

                    ClientOrder clientOrder = new ClientOrder();
                    clientOrder.setStatus("NEW");
                    clientOrder.setCreated(Calendar.getInstance().getTime());
                    clientOrder.setLastAction(clientOrder.getCreated());

                    Object obj;

                    Integer placeId = 0;
                    obj = jObj.get("placeId");
                    if (obj != null) {
                        placeId = ((Long)obj).intValue();
                        Place place = new Place();
                        place.setId(placeId);
                        clientOrder.setPlace(place);
                    }
                    //clientOrderService.save(clientOrder);


                    obj = jObj.get("content");
                    if (obj != null && obj instanceof JSONArray) {
                        JSONArray array = (JSONArray)obj;
                        int n = array.size();
                        if (n > 0) {
                            List<ClientOrderContent> content = new ArrayList<>(n);
                            for (int i = 0; i < n; i++) {
                                Object o = array.get(i);
                                ClientOrderContent coc = new ClientOrderContent();
                                coc.setClientOrder(clientOrder);
                                coc.setJSON((JSONObject) o);
                                content.add(coc);
                            }
                            clientOrder.setContent(content);
                            clientOrderService.save(clientOrder);
                        }
                    }

                } catch (ParseException e) {
                    log.error("try to parse json" + e);
                }
            }


            out.print("ok");
            out.flush();
            out.close();
        } catch (IOException ex) {
            log.error("addOrder {}", ex);
        }
    }
/*
    @RequestMapping(value = "/infoOrder")
    public void infoOrder(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse) {
        try {

            String json = httpRequest.getParameter("order");

            initJSONHeader(httpResponse);
            PrintWriter out = httpResponse.getWriter();
            for (String st:orders){
                out.println(st);
            }

            out.flush();
            out.close();
        } catch (IOException ex) {
            log.error("infoOrder {}", ex);
        }
    }
    */
}
